import { onBeforeUnmount, ref } from 'vue'

export default function useDebounce(fn: any, delay: number) {
  const timerRef = ref()
  onBeforeUnmount(() => {
    if (timerRef.value) {
      clearTimeout(timerRef.value)
      timerRef.value = null
    }
  })
  return (...args: any) => {
    if (timerRef.value) clearTimeout(timerRef.value)
    timerRef.value = setTimeout(() => fn(...args), delay)
  }
}
